package com.bckj.fastboot.security.util;

import com.bckj.fastboot.core.lang.exception.BusinessException;
import com.bckj.fastboot.security.model.AuthUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 安全工具类
 *
 * @author L.cm
 */
@UtilityClass
public class SecurityUtils {

	/**
	 * 获取Authentication
	 */
	public Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	/**
	 * 获取用户
	 */
	public AuthUser getUser(Authentication authentication) {
		Object principal = authentication.getPrincipal();
		if (principal instanceof AuthUser) {
			return (AuthUser) principal;
		}
		return null;
	}

	/**
	 * 获取用户
	 */
	public Optional<AuthUser> getUser() {
		return Optional.ofNullable(getAuthentication()).map(SecurityUtils::getUser);
	}

	/**
	 * 获取用户失败抛异常
	 */
	public AuthUser getUserOrElseThrow() {
		return getUser().orElseThrow(() -> new BusinessException("获取用户信息失败"));
	}

}
